import { defineStore } from 'pinia'
import {ref,computed} from 'vue' 
export const useCounterStore = defineStore('counter', () => {

    //定义一个购物车列表
   const cartList = ref([])
     //定义一个订单列表
    const myOrderList = ref([])
   //加入购物车判断
   const addItem = (playload)=>{
       const index = cartList.value.findIndex(item=>item.id==playload.id)
       if(index > -1)
       {
          cartList.value[index].count++
       }else
       {
           cartList.value.push({
            ...playload,
            count:1,
            checked:false
           })
       }
   }

   //购物车删除
   const cartDelItem = (id) =>{
    cartList.value = cartList.value.filter(item=>item.id != id)
   }

   //数量加
   const addCount =(id)=>{
       cartList.value.find(item=>item.id==id).count++
   }

    //数量减
   const subCount =(id)=>{
       cartList.value.find(item=>item.id==id).count--
   }

   //购物车总数量
   const totalCount = computed(()=>{
      let res = 0
      cartList.value.forEach(item=>{
        res += item.count
      })
      return res
   })

   //购物车总价格
   const totalPrice = computed(()=>{
    let res =0 
    cartList.value.forEach(item=>{
          if(item.checked==true){
              res += item.count*item.price
          }
    })
    return res.toFixed(2)
   })

   //订单列表
   const orderList = computed(()=>{
    return cartList.value.filter(item=>item.checked==true)
   })
   //添加订单列表
   const addOrderList = (payload)=>{
       myOrderList.value.push(payload)
   }
 
   //订单状态
   const updateSatus =()=>{
      myOrderList.value.find(item=>item.id==id).status=2
   }
  return { cartList,addItem,cartDelItem,addCount,subCount,totalCount,totalPrice,myOrderList,orderList,addOrderList,updateSatus}
},{
    persist:true
})